package com.ljpz.web.interceptors;

import com.ljpz.common.utils.CookieUtils;
import com.ljpz.sso.query.bean.User;
import com.ljpz.web.service.UserService;
import com.ljpz.web.threadLocal.UserThreadLocal;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by liujunchen on 2016/12/23.
 */
public class UserLoginHanderInterceptor  implements HandlerInterceptor{
    public   static  final String   COOKIE_NAME="LJPZ_TOKEN" ;
    @Autowired
    private UserService userService  ;
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        UserThreadLocal.set(null);
        String   token= CookieUtils.getCookieValue(request,COOKIE_NAME) ;
        String loginUrl=this.userService.LJPZ_SSO_URL+"/user/login.html";
        if (StringUtils.isEmpty(token)){
            //未登录，跳转到登录页面
            response.sendRedirect(this.userService.LJPZ_SSO_URL+"/user/login.html");
            return  false  ;
        }
        User user = this.userService.queryByToken(token)  ;
        if (null==user){
            //登录超时，跳转到登录页面
            response.sendRedirect(loginUrl );
            return  false  ;
        }
        //登录成功
        UserThreadLocal.set(user);//将user对象放置到本地线程中，方便在controller和service中获取
        return  true ;

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
